<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>成远生产管控平台 - 车辆信息</title>
    <link rel="stylesheet" href="./layui/css/layui.css"/>
    <script src="./layui/layui.js"></script>
    <script>
        // 全局配置
        window.appConfig = {
            //apiBaseUrl: 'http://localhost:8080' // 开发环境
            apiBaseUrl: 'http://59.110.144.74:8080' // 生产环境
        };
    </script>

    <style>
        body {
            padding: 20px;
        }
    </style>
</head>
<body>

<div class="layui-container" style="padding: 20px;">
    <form class="layui-form" id="truckUnitForm" lay-filter="truckUnitForm">
        <input type="hidden" name="id" id="truckUnitId">

        <div class="layui-form-item">
            <label class="layui-form-label">车牌号</label>
            <div class="layui-input-block">
                <input type="text" name="plate" id="plate" required lay-verify="required|plate"
                       placeholder="请输入车牌号" class="layui-input">
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">车辆类型</label>
            <div class="layui-input-block">
                <select name="truckTypeName" id="truckTypeName" lay-verify="required" lay-search>
                    <!-- 车辆类型动态加载 -->
                </select>
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">所属单位</label>
            <div class="layui-input-block">
                <select name="unitName" id="unitName" lay-verify="required" lay-search>
                    <!-- 单位列表动态加载 -->
                </select>
            </div>
        </div>

        <div class="layui-form-item">
            <div class="layui-input-block">
                <button class="layui-btn" lay-submit lay-filter="saveTruckUnit">保存</button>
                <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                <button type="button" class="layui-btn layui-btn-danger" onclick="window.history.back()">返回</button>
            </div>
        </div>
    </form>
</div>

<script>
    layui.use(['form', 'layer', 'jquery'], function () {
        const form = layui.form;
        const layer = layui.layer;
        const $ = layui.jquery;

        // 加载车辆类型
        async function loadTruckTypes() {
            try {
                const res = await $.get(window.appConfig.apiBaseUrl +'/truck-type/all');
                console.log('车辆类型接口返回:', res); // ← 添加日志确认结构
                if (res && Array.isArray(res.data)) {
                    $('#truckTypeName').empty(); // 清空原有选项
                    res.data.forEach(type => {
                        $('#truckTypeName').append(`<option value="${type.truckTypeName}">${type.truckTypeName}</option>`);
                    });
                    form.render('select'); // 重新渲染下拉框
                } else {
                    layer.msg('车辆类型数据为空或格式错误', {icon: 2});
                }
            } catch (error) {
                console.error('加载车辆类型失败:', error);
                layer.msg('加载车辆类型失败', {icon: 2});
            }
        }

        // 加载单位数据
        async function loadUnits() {
            try {
                const res = await $.get(window.appConfig.apiBaseUrl +'/unit/all');
                if (res.code === 200 && Array.isArray(res.data)) {
                    res.data.forEach(unit => {
                        $('#unitName').append(`<option value="${unit.unitName}">${unit.unitName}</option>`);
                    });
                    form.render('select');
                } else {
                    layer.msg('单位数据加载失败', {icon: 2});
                }
            } catch (error) {
                console.error('加载单位失败:', error);
                layer.msg('网络请求失败', {icon: 2});
            }
        }

        // 初始化数据（如果是编辑）
        const urlParams = new URLSearchParams(window.location.search);
        const mode = urlParams.get('mode');
        const truckUnitId = urlParams.get('id');
        const plate = urlParams.get('plate');
        const truckTypeName = urlParams.get('truckTypeName');
        const unitName = urlParams.get('unitName');

        loadUnits().then(() => {
            loadTruckTypes().then(() => {
                if (mode === 'edit' && truckUnitId) {
                    $('#truckUnitId').val(truckUnitId);
                    $('#plate').val(plate);
                    $('#truckTypeName').val(truckTypeName);
                    $('#unitName').val(unitName);
                    form.render();
                }
            });
        });

        // 表单提交事件
        form.on('submit(saveTruckUnit)', function (data) {
            const formData = data.field;
            const isEdit = !!formData.id;

            $.ajax({
                url: window.appConfig.apiBaseUrl +'/truck-unit',
                method: isEdit ? 'PUT' : 'POST',
                contentType: 'application/json',
                data: JSON.stringify(formData),
                success: function (res) {
                    if (res.code === 0) {
                        layer.msg(isEdit ? '更新成功' : '添加成功', {icon: 1});
                        window.location.href = 'admin.html#truckUnit';
                    } else {
                        layer.msg(res.message || '操作失败', {icon: 2});
                    }
                },
                error: function (xhr) {
                    layer.msg('请求失败: ' + xhr.statusText, {icon: 2});
                }
            });

            return false; // 阻止默认提交
        });
    });
</script>

</body>
</html>
